using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace SCIENEW {
    public static class DeviceEntityUtils {
        /// <summary>
        /// 为某个设备创建实体
        /// </summary>
        /// <param name="subsystemTerrain"></param>
        /// <param name="entityName"></param>
        /// <param name="position"></param>
        public static Entity CreateDeviceEntity(SubsystemTerrain subsystemTerrain, string entityName, Point3 position) {
            DatabaseObject databaseObject = subsystemTerrain.Project.GameDatabase.Database.FindDatabaseObject(entityName, subsystemTerrain.Project.GameDatabase.EntityTemplateType, throwIfNotFound: true);
            var valuesDictionary = new ValuesDictionary();
            valuesDictionary.PopulateFromDatabaseObject(databaseObject);
            valuesDictionary.GetValue<ValuesDictionary>("BlockEntity").SetValue("Coordinates", position);
            Entity entity = subsystemTerrain.Project.CreateEntity(valuesDictionary);
            subsystemTerrain.Project.AddEntity(entity);
            return entity;
        }

        /// <summary>
        /// 移除设备的实体
        /// </summary>
        /// <param name="subsystemTerrain"></param>
        /// <param name="position"></param>
        public static void RemoveDeviceEntity(SubsystemTerrain subsystemTerrain, Point3 position) {
            ComponentBlockEntity blockEntity = subsystemTerrain.Project.FindSubsystem<SubsystemBlockEntities>(throwOnError: true).GetBlockEntity(position.X, position.Y, position.Z);
            if (blockEntity != null)
            {
                Vector3 centerPos = new Vector3(position) + new Vector3(0.5f);
                foreach (IInventory item in blockEntity.Entity.FindComponents<IInventory>())
                {
                    item.DropAllItems(centerPos);
                }
                subsystemTerrain.Project.RemoveEntity(blockEntity.Entity, disposeEntity: true);
            }
        }

        /// <summary>
        /// 获得设备的实体
        /// </summary>
        /// <param name="subsystemTerrain"></param>
        /// <param name="position"></param>
        /// <param name="blockEntity"></param>
        /// <returns></returns>
        public static bool GetDeviceEntity(SubsystemTerrain subsystemTerrain, Point3 position, out ComponentBlockEntity blockEntity) {
            blockEntity = subsystemTerrain.Project.FindSubsystem<SubsystemBlockEntities>(throwOnError: true).GetBlockEntity(position.X, position.Y, position.Z);
            return blockEntity != null;
        }
    }
}